
#include <stdio.h>
#include <stdlib.h>
// #include <string.h>
#include <signal.h>

#include "tcpa_monitor.h"
#include "tcpa_util.h"

// 加速监测上下文指针
tcpa_monitor_t *tcpa_monitor;

void sig_handler(int sig)
{
    TCPAM_LOG_INFO("receive signal: %d", sig);
    tcpa_monitor_stop(tcpa_monitor);
    tcpa_monitor_destroy(tcpa_monitor);
    exit(0);
}

void init_signal(void) 
{
    // SIGINT信号（通常是Ctrl+C触发的中断信号）与sig_handler函数关联起来。
    signal(SIGINT, sig_handler);
    // 当系统关闭或重启、使用kill命令或系统管理工具，会触发SIGTERM信号
    signal(SIGTERM, sig_handler);
}


int main(int argc, char* argv[])
{
    // 检查是否以root权限启动
    if (geteuid() != 0) {
        TCPAM_LOG_ERROR("please run as root.");
        return -1;
    }

    // TCPAM_LOG_INFO("***** src_code PATH:%s *****", CURRENT_DIR);
    // 配置文件路径参数解析
    tcpa_monitor = tcpa_monitor_create();
    if (tcpa_monitor == NULL) {
        TCPAM_LOG_ERROR("create tcpa_monitor fail.");
        return -1;
    }
    // 解析输入参数
    if (decode_input_parameter(argc, argv, tcpa_monitor) < 0) {
        TCPAM_LOG_ERROR("decode input parameter fail.");
        return -1;
    }
    // 解析rcstnetcfg
    if (read_rcstnetcfg_json(tcpa_monitor) < 0) {
        TCPAM_LOG_ERROR("create tcpa_cfg_file fail.");
        return -1;
    }    
    
    // 初始化信号捕获处理
    init_signal();

    // 启动提示信息
    TCPAM_LOG_INFO("**********************************************************************"); 
    TCPAM_LOG_INFO("hello. this is TCPA_monitor."); 
    TCPAM_LOG_INFO("version:%s. build_time: %s %s", TCPA_MONITOR_VERSION, __DATE__, __TIME__);

    // 初始化并启动监测器
    tcpa_monitor->monitor_status = TCPA_MONITOR_STATUS_START;
    if (tcpa_monitor_init(tcpa_monitor) < 0) {
        TCPAM_LOG_ERROR("start tcpa_monitor fail.");
        tcpa_monitor->monitor_status = TCPA_MONITOR_STATUS_ABNORMAL;
        return -1;
    }
    tcpa_monitor->monitor_status = TCPA_MONITOR_STATUS_RUNNING;
    TCPAM_LOG_INFO("start tcpa_monitor success. see tcpam_info: %s", TCPA_MONITOR_PROC_PATH);
    TCPAM_LOG_INFO("**********************************************************************"); 
    
    // 启动监听
    while (tcpa_monitor->monitor_status == TCPA_MONITOR_STATUS_RUNNING) {
        // 保活监测与配置更新需要互斥
        pthread_mutex_lock(&tcpa_monitor->cfg_mutex);
        listen_tcpa_running(tcpa_monitor);
        pthread_mutex_unlock(&tcpa_monitor->cfg_mutex);
        sleep(1);
    }
    // 等待清理完成后退出
    while (tcpa_monitor->monitor_status != TCPA_MONITOR_STATUS_STOP) {
        usleep(100000);
    }
    
    return 0;
}

